package com.tangcco.lockwell.controller.common;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.tangcco.lockwell.base.RestResponse;
import com.tangcco.lockwell.base.SystemCode;
import com.tangcco.lockwell.context.WebContext;
import com.tangcco.lockwell.domain.DataDictionary;
import com.tangcco.lockwell.domain.SubjectDto;
import com.tangcco.lockwell.domain.User;
import com.tangcco.lockwell.domain.UserToken;
import com.tangcco.lockwell.service.DataDictionaryService;
import com.tangcco.lockwell.service.GroupsService;
import com.tangcco.lockwell.service.UserService;
import com.tangcco.lockwell.service.UserTokenService;
import com.tangcco.lockwell.utility.StudentSubjectUtil;
import com.tangcco.lockwell.viewmodel.admin.groups.GroupsPageFindVM;
import com.tangcco.lockwell.viewmodel.admin.user.UserResponseVM;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author yanxinping
 * @date 2021/10/27 16:22
 * 用户token相关接口
 */
@RestController
@RequestMapping("/api/userToken")
public class UserTokenController {
    private static final Logger logger = Logger.getLogger(UserTokenController.class);

    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private UserService userService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private WebContext webContext;
    @Autowired
    private StudentSubjectUtil studentSubjectUtil;
    @Autowired
    private GroupsService groupsService;

    /**
     * 根据用户token获取用户信息
     */
    @RequestMapping(value = "/getUserByToken", method = RequestMethod.GET)
    public RestResponse<User> getUserByToken(@RequestParam(value = "token") String token) {
        UserToken userToken = userTokenService.getToken(token);
        if (userToken == null || userToken.getUserId() == null) {
            return RestResponse.fail(SystemCode.InnerError.getCode(), "token不存在");
        }
        User user = userService.getUserById(userToken.getUserId());
        if (user == null) {
            return RestResponse.fail(SystemCode.InnerError.getCode(), "用户不存在");
        }

        System.out.println(studentSubjectUtil.getSubjectIdByUser("math"));

        return RestResponse.ok(user);
    }
    //用户详情
    @RequestMapping(value = "/getUserById/{id}")
    public RestResponse<UserResponseVM> getUserById(@PathVariable Integer id) {
        User user = userService.getUserById(id);
        UserResponseVM userResponseVM = BeanUtil.copyProperties(user, UserResponseVM.class);
        if(Objects.nonNull(user) && Objects.nonNull(user.getOptSubject())) {
            List<SubjectDto> subjectDtos = new ArrayList<>();
            String[] subject = user.getOptSubject().split(",");
            Arrays.stream(subject).forEach(s -> {
                DataDictionary dataDictionary = dataDictionaryService.selectById(Integer.parseInt(s));
                SubjectDto subjectDto = new SubjectDto();
                subjectDto.setName(dataDictionary.getCategoryName());
                subjectDto.setSubjectId(dataDictionary.getId());
                subjectDto.setPath(dataDictionary.getDescription());
                if(dataDictionary.getParentId()!=null){
                    //查询父级
                    DataDictionary parentData = dataDictionaryService.selectById(dataDictionary.getParentId());
                    subjectDto.setParentName(parentData.getCategoryName());
                }else{
                    subjectDto.setParentName(dataDictionary.getCategoryName());
                }

                subjectDtos.add(subjectDto);
            });
            userResponseVM.setSubjects(subjectDtos);
        }
        //群组信息
        List<GroupsPageFindVM> groupList = groupsService.findGroupByUserId(id);
        if(CollectionUtil.isNotEmpty(groupList)){
            userResponseVM.setGroupName(groupList.stream().map(GroupsPageFindVM::getGroupName).filter(groupName -> groupName !=null).collect(Collectors.joining(",")));
        }
        return RestResponse.ok(userResponseVM);
    }

    /**
     * 修改用户选择的科目
     * @param optSubjectIds
     * @return
     */
    @RequestMapping(value = "/updateUserOptSubjet")
    public RestResponse updateUserOptSubje(@RequestParam(value = "optSubjectIds") String optSubjectIds){
        User u = new User();
        u.setOptSubject(optSubjectIds);
        u.setUserId(webContext.getCurrentUser().getUserId());
        userService.updateByIdFilter(u);
        return RestResponse.ok();
    }
}
